package com.ruoyi.project.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.ruoyi.common.utils.AlibabaApi;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.project.system.domain.SysEarnings;
import com.ruoyi.project.system.domain.SysQuery;
import com.ruoyi.project.system.domain.SysQueryPay;
import com.ruoyi.project.system.domain.vo.Promote;
import com.ruoyi.project.system.mapper.SysEarningsMapper;
import com.ruoyi.project.system.mapper.SysQueryPayMapper;
import com.ruoyi.project.system.service.ISysProductService;
import com.ruoyi.project.system.service.ISysQueryPayService;
import com.ruoyi.project.system.service.ISysQueryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 进件查询支付Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-23
 */
@Slf4j
@Service
public class SysQueryPayServiceImpl implements ISysQueryPayService {

    @Autowired
    private ISysQueryService iSysQueryService;

    @Autowired
    private ISysProductService iSysProductService;

    @Autowired
    private SysQueryPayMapper sysQueryPayMapper;

    @Autowired
    private SysEarningsMapper sysEarningsMapper;

    @Value("${back-domain}")
    private String backDomain;

    @Value("${front-domain}")
    private String frontDomain;

    public static String[] paths = {"bdp", "bd", "com", "check", "jud", "imm"};

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int refund(SysQueryPay sysQueryPay) throws Exception {
        SysQueryPay pay = sysQueryPayMapper.selectSysQueryPayByOrderNo(sysQueryPay.getOrderNo());
        SysQueryPay refund = new SysQueryPay().setOrderNo(sysQueryPay.getOrderNo()).setPayState("REFUND");
        refund.setRemark(sysQueryPay.getRemark());
        if (StringUtils.isEmpty(pay.getBrokerageId())){
            refund.setRefundDis("2");
        } else {
            refund.setRefundDis("1");
        }
        if (StringUtils.isEmpty(pay.getRoyaltyId())){
            refund.setRefundDis_("2");
        } else {
            refund.setRefundDis_("1");
        }
        sysQueryPayMapper.updateSysQueryPay(refund);

        List<SysEarnings> sysEarnings = sysEarningsMapper.selectSysEarningsList(new SysEarnings().setSourceId(sysQueryPay.getOrderNo()));
        for (SysEarnings earnings: sysEarnings){
            if (StringUtils.isEmpty(earnings.getExtractId())){
                sysEarningsMapper.updateSysEarnings(earnings.setRefundDis("2"));
            }else {
                sysEarningsMapper.updateSysEarnings(earnings.setRefundDis("1"));
            }
        }
//        System.out.println("---操作退款---: "+ sysQueryPay);
//        return 1;
        AlipayTradeRefundResponse refundResponse = AlibabaApi.refund(sysQueryPay);
        if ("10000".equals(refundResponse.getCode()) && "Success".equals(refundResponse.getMsg())) {
            return 1;
        }else {
            throw new Exception(refundResponse.getSubMsg());
        }
    }

    @Override
    @Transactional
    public JSONObject createPayInfo(SysQueryPay sqp) throws IOException {
        // 1 拉起进件订单
        SysQuery sysQuery = iSysQueryService.selectSysQueryById(sqp.getQueryId());
        // 2 拉起产品价格信息
        Promote promote = iSysProductService.calculatePriceInfo(sysQuery.getUserId(), sysQuery.getProductId());
        // 3 合成支付订单
        sqp = makeQueryPay(sqp, sysQuery, promote);
        // 4 保存
        insertSysQueryPay(sqp);
        // 5 拉起支付
        JSONObject zhifuFM = zhifuFM(sqp, paths[sysQuery.getProductId() - 1]);
//        JSONObject zhifuFM = null;
        return zhifuFM;
    }

    public SysQueryPay makeQueryPay(SysQueryPay sqp, SysQuery sysQuery, Promote promote) {
        sqp.setSysFloorPrice(promote.getSysFloorPrice());
        sqp.setRoyalty(promote.getRoyalty());
        sqp.setFloorPrice(promote.getFloorPrice());
        sqp.setBrokerage(promote.getBrokerage());
        sqp.setPricing(promote.getPricing());
        sqp.setRedPacketNum(promote.getRedPacketNum());
        sqp.setPayState("NOTPAY");
        sqp.setPayType("alipaysign");
        sqp.setSubject(promote.getProductName());
        sqp.setBody(promote.getProductId() + "");

        String key = StringUtils.isNotEmpty(sysQuery.getName()) ? sysQuery.getName() + "::" : "";
        key += StringUtils.isNotEmpty(sysQuery.getCardNo()) ? sysQuery.getCardNo() + "::" : "";
        key += StringUtils.isNotEmpty(sysQuery.getMobile()) ? sysQuery.getMobile() + "::" : "";
        key = key.substring(0, key.length() - 2);
        sqp.setKeyword(key);
        return sqp;
    }

    public JSONObject zhifuFM(SysQueryPay sqp, String path) throws IOException {
//      容易查
        String merchantNum = "469564016919199744";             // 商户号
        String secretKey = "4892e432d23ced12d3b6825c11718181";  // 商户密钥
        String sign = merchantNum + sqp.getOrderNo() + sqp.getPricing() + backDomain + secretKey;
        sign = Md5Utils.hash(sign);                             // md5签名
        Map<String, String> paramMap = new HashMap<>();         // post请求的参数
        paramMap.put("merchantNum", merchantNum);
        paramMap.put("orderNo", sqp.getOrderNo());
        paramMap.put("amount", sqp.getPricing().toString());
        paramMap.put("notifyUrl", backDomain);    // 填写您的接收支付成功的异步通知地址
        paramMap.put("returnUrl", frontDomain + path);

        paramMap.put("payType", sqp.getPayType());
        paramMap.put("sign", sign);
        paramMap.put("subject", "tianqi");
        log.info("支付请求参数：" + paramMap);
        String result;
        JSONObject ret = new JSONObject();
        String paramStr = StringUtils.toParams(paramMap);

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost httpost = new HttpPost("http://api-albd2vor5wqo.zhifu.fm.it88168.com/api/startOrder?" + paramStr); // 设置响应头信息
        String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";
        httpost.setHeader("User-Agent", userAgent);     //防止被防火墙拦截 Apache httpclient
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(5000).build();
        httpost.setConfig(requestConfig);
        HttpResponse retResp = httpclient.execute(httpost);
        result = EntityUtils.toString(retResp.getEntity(), "UTF-8");
        if (result.startsWith("{")) { //为了您的业务健壮性，建议简单判断或者增加下容错逻辑
            ret = JSONObject.parseObject(result);
        } else {
            ret.put("code", "error");
            ret.put("result", result);
            ret.put("msg", "发起支付订单失败，接口返回信息异常");
        }
        return ret;
    }

    /**
     * 查询进件查询支付
     *
     * @param orderNo 进件查询支付主键
     * @return 进件查询支付
     */
    @Override
    public SysQueryPay selectSysQueryPayByOrderNo(String orderNo) {
        return sysQueryPayMapper.selectSysQueryPayByOrderNo(orderNo);
    }

    /**
     * 查询进件查询支付列表
     *
     * @param sysQueryPay 进件查询支付
     * @return 进件查询支付
     */
    @Override
    public List<SysQueryPay> selectSysQueryPayList(SysQueryPay sysQueryPay) {
        return sysQueryPayMapper.selectSysQueryPayList(sysQueryPay);
    }

    /**
     * 新增进件查询支付
     *
     * @param sysQueryPay 进件查询支付
     * @return 结果
     */
    @Override
    public int insertSysQueryPay(SysQueryPay sysQueryPay) {
        sysQueryPay.setCreateTime(DateUtils.getNowDate());
        return sysQueryPayMapper.insertSysQueryPay(sysQueryPay);
    }

    /**
     * 修改进件查询支付
     *
     * @param sysQueryPay 进件查询支付
     * @return 结果
     */
    @Override
    public int updateSysQueryPay(SysQueryPay sysQueryPay) {
        return sysQueryPayMapper.updateSysQueryPay(sysQueryPay);
    }

    /**
     * 批量删除进件查询支付
     *
     * @param orderNos 需要删除的进件查询支付主键
     * @return 结果
     */
    @Override
    public int deleteSysQueryPayByOrderNos(String[] orderNos) {
        return sysQueryPayMapper.deleteSysQueryPayByOrderNos(orderNos);
    }

}
